package com.cg.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.cg.common.PayCommon;
import com.cg.config.PayEntity;
import com.cg.entity.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @ClassName PayAlibabaServiceImpl
 * @Description 支付宝支付
 * @Author CG
 * @Date 2024/1/15 10:49
 **/
@Service("payAlibabaServiceImpl")
public class PayAlibabaServiceImpl implements PayService{

    @Resource
    private PayEntity payEntity;

    /**
     * 支付宝支付
     * @param order
     * @return
     */
    @Override
    public String toPay(Order order) {
        String privateKey = payEntity.getPrivateKey();
        String alipayPublicKey = payEntity.getAlipayPublicKey();
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl(payEntity.getServerUrl());
        alipayConfig.setAppId(payEntity.getAppId());
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat(payEntity.getFormat());
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset(payEntity.getCharset());
        alipayConfig.setSignType(payEntity.getSignType());
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(alipayConfig);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(order.getOrderNum());
        model.setTotalAmount(order.getPrice().toString());
        model.setSubject(PayCommon.ALT_ORDER_SUBJECT);
        model.setProductCode(payEntity.getProductCode());
        request.setBizModel(model);
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request, "POST");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        // 如果需要返回GET请求，请使用
        // AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();
        System.out.println("pageRedirectionData:"+pageRedirectionData);
        System.out.println(pageRedirectionData);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return pageRedirectionData;
    }
}
